<template>
    <div>
         <div style="margin: 20px 20px;" class="btn_box">
            <el-button type="primary" @click="handlerAdd">新增专业</el-button>
        </div>
        <el-table :data="majors" style="width: 100%;height: 380px;" border>
            <el-table-column type="index" label="序号" width="60"></el-table-column>
            <el-table-column type="majorname" label="专业名称" prop="majorname"></el-table-column>
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button @click="handleEdit(scope.row._id)">
                        编辑
                    </el-button>
                    <el-button type="danger" @click="handleDelete(scope.row._id)">
                        删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
            layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />

        <!-- 新增专业 -->
        <el-dialog v-model="majorFromVisible" :title="title" width="500">
            <el-form :model="majorFrom" ref="majorFormRef" :rules="rules">
                <el-form-item label="专业名称" prop="majorname">
                    <el-input v-model="majorFrom.majorname" @keydown.enter = "submitForm(majorFormRef)"/>
                </el-form-item>
                
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm(majorFormRef)">
                        确定
                    </el-button>
                    <el-button @click="majorFromVisible = false">取消</el-button>
                    
                </div>
            </template>
        </el-dialog>
    </div>
</template>
<script setup lang="ts">
import type { majorInfoData, pageMajorData } from '@/api/major/type';
import useMajorStore from '@/store/modules/major';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import { nextTick, onMounted, reactive, ref } from 'vue';
const majorStore = useMajorStore();
/* 获取学校的分页查询 */
//当前页码:
const currentPage = ref(1);
//每页展示多少
const pageSize = ref(5);
//分页返回的总条数
const total = ref(0)
const majors = ref<majorInfoData[]>()
const majorFormRef = ref()
const majorFrom = ref<majorInfoData>({
    _id:undefined,
    majorname:""
})
const title = ref();
//分页查询方法
const PageQuery = (size: number, page: number) => {
    let pagArg = reactive<pageMajorData>({
        page: page,
        size: size
    })
    majorStore.pageMajor(pagArg).then((res) => {
        majors.value = res.data as majorInfoData[];
        total.value = res.total;
    })
}
//显示条数大小改变的时候触发的方法
const handleSizeChange = (val: number) => {
    pageSize.value = val;
    PageQuery(pageSize.value,currentPage.value)
    console.log(`当前一页总条数:${val}`);
}
//改变当前页面
const handleCurrentChange = (val: number) => {
    currentPage.value = val;
    PageQuery(pageSize.value,currentPage.value)
    console.log(`当前页码:${val}`);
}

/* 新增专业 */
//控制新增对话框显隐
const majorFromVisible = ref(false);
const handlerAdd = ()=>{
    majorFromVisible.value = true;
    title.value = "新增专业"
    nextTick(()=>{
        majorFormRef.value.resetFields();
    })
}
/* 编辑专业信息 */
const handleEdit = (_id:string)=>{
    console.log("_id:",_id);
    
    majorFromVisible.value = true;
    title.value = "编辑专业";
    majorStore.findById(_id).then((res)=>{
        majorFrom.value = {...res};
        console.log(majorFrom.value);
        
    })
}
const checkMajorlName = (rule: any, value: any, callback: any) => {
    value = value.trim();
  if (value == "") {
    return callback(new Error('请输入专业名称'))
  }else{
    return callback();
  }
}
const rules = reactive<FormRules>({
  name: [{ required:true,validator: checkMajorlName, trigger: 'blur' }],
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
        if(title.value == "新增专业"){
            //验证都成功后,发送添加请求
        majorStore.addMajor(majorFrom.value).then(()=>{
            //刷新页面
            PageQuery(pageSize.value, currentPage.value);
            //关掉对话框
            majorFromVisible.value = false
            ElMessage({
                type:'success',
                message:"添加成功"
            })
        }).catch((err)=>{
            majorFromVisible.value = false
            ElMessage({
                type:"error",
                message:err.msg
            })
        })
        }else if(title.value == "编辑专业"){
            //编辑学校的校验
            majorStore.updateMajor(majorFrom.value).then(()=>{
                //刷新页面
                PageQuery(pageSize.value, currentPage.value);
                //关掉对话框
                majorFromVisible.value = false
                ElMessage({
                type:'success',
                message:"修改成功"
                })
            }).catch((err)=>{
                majorFromVisible.value = false
                ElMessage({
                    type:"error",
                    message:err.msg
                })
            })
            
        }
    } else {
      console.log('error submit!')
    }
  })
}

/* 删除专业 */
const handleDelete = (_id: string) => {
    majorStore.deleteMajor(_id).then(() => {
        //删除成功
       PageQuery(pageSize.value, currentPage.value)
        ElMessage({
            type: "success",
            message: "删除成功"
        })
    }).catch((err)=>{
        ElMessage({
            type: "error",
            message: err.msg
        })
    })

}
onMounted(() => {
    PageQuery(pageSize.value, currentPage.value)
})
</script>

<style scoped>
.el-pagination {
    display: flex;
    justify-content: center;
}
</style>